<template>
  <div class="rate-submit">
    <el-card class="rate-card">
      <template #header>
        <div class="card-header">
          <el-button @click="goBack" :icon="ArrowLeft">返回</el-button>
          <span class="title">评价受托方</span>
        </div>
      </template>
      
      <!-- 委托信息展示 -->
      <div class="entrust-info">
        <h3>委托信息</h3>
        <div class="info-item">
          <span class="label">委托标题：</span>
          <span class="value">{{ entrustInfo.title }}</span>
        </div>
        <div class="info-item">
          <span class="label">受托方：</span>
          <span class="value">{{ entrustInfo.acceptor?.name }}</span>
        </div>
        <div class="info-item">
          <span class="label">完成时间：</span>
          <span class="value">{{ formatTime(entrustInfo.completeTime) }}</span>
        </div>
      </div>
      
      <!-- 评价表单 -->
      <el-form 
        ref="formRef"
        :model="rateForm"
        :rules="rules"
        label-width="100px"
        class="rate-form"
      >
        <el-form-item label="服务评分" prop="rating">
          <div class="rating-section">
            <el-rate
              v-model="rateForm.rating"
              :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
              show-text
              :texts="['很差', '较差', '一般', '较好', '很好']"
              @change="handleRatingChange"
            />
            <div class="rating-tip">
              请根据服务质量给出客观评价
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="评价内容" prop="content">
          <el-input
            v-model="rateForm.content"
            type="textarea"
            :rows="6"
            placeholder="请详细描述您的服务体验，至少10个字"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="评价标签">
          <div class="tag-section">
            <el-tag
              v-for="tag in availableTags"
              :key="tag"
              :type="selectedTags.includes(tag) ? 'primary' : 'info'"
              class="tag-item"
              @click="toggleTag(tag)"
            >
              {{ tag }}
            </el-tag>
          </div>
        </el-form-item>
        
        <el-form-item label="匿名评价">
          <el-switch
            v-model="rateForm.isAnonymous"
            active-text="匿名发布"
            inactive-text="显示姓名"
          />
          <div class="anonymous-tip">
            开启后您的姓名将不会在评价中显示
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            size="large"
            :loading="submitLoading"
            @click="handleSubmit"
          >
            提交评价
          </el-button>
          <el-button 
            size="large"
            @click="handleSave"
          >
            保存草稿
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'

/**
 * 评价提交页面组件
 * @description 用于用户对受托方进行评价
 */
const route = useRoute()
const router = useRouter()

// 组件状态
const formRef = ref(null)
const submitLoading = ref(false)

// 委托信息
const entrustInfo = ref({})

// 评价表单数据
const rateForm = reactive({
  rating: 0,
  content: '',
  tags: [],
  isAnonymous: false
})

// 可选标签
const availableTags = [
  '服务态度好',
  '准时完成',
  '沟通顺畅',
  '质量满意',
  '价格合理',
  '响应及时',
  '专业负责',
  '耐心细致'
]

// 已选标签
const selectedTags = ref([])

// 表单验证规则
const rules = {
  rating: [
    { required: true, message: '请选择服务评分', trigger: 'change' },
    { type: 'number', min: 1, message: '评分不能为0', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入评价内容', trigger: 'blur' },
    { min: 10, max: 500, message: '评价内容长度在10到500个字符之间', trigger: 'blur' }
  ]
}

// 模拟委托信息
const mockEntrustInfo = {
  id: 1,
  title: '代取快递',
  acceptor: {
    name: '李同学',
    avatar: ''
  },
  completeTime: '2023-11-30T15:30:00Z'
}

/**
 * 格式化时间显示
 * @param {string} timeStr - 时间字符串
 * @returns {string} 格式化后的时间
 */
const formatTime = (timeStr) => {
  if (!timeStr) return '未知'
  const time = new Date(timeStr)
  return time.toLocaleString('zh-CN')
}

/**
 * 处理评分变化
 * @param {number} value - 评分值
 */
const handleRatingChange = (value) => {
  console.log('评分变化：', value)
  // 根据评分自动推荐标签
  if (value >= 4) {
    const positiveTags = ['服务态度好', '准时完成', '质量满意', '专业负责']
    selectedTags.value = positiveTags.filter(tag => 
      availableTags.includes(tag)
    )
  } else if (value <= 2) {
    selectedTags.value = []
  }
}

/**
 * 切换标签选择
 * @param {string} tag - 标签名称
 */
const toggleTag = (tag) => {
  const index = selectedTags.value.indexOf(tag)
  if (index > -1) {
    selectedTags.value.splice(index, 1)
  } else {
    if (selectedTags.value.length < 5) {
      selectedTags.value.push(tag)
    } else {
      ElMessage.warning('最多只能选择5个标签')
    }
  }
}

/**
 * 获取委托信息
 */
const fetchEntrustInfo = async () => {
  try {
    // TODO: 调用API获取委托信息
    // const res = await getEntrustInfo(route.params.id)
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 300))
    
    entrustInfo.value = { ...mockEntrustInfo }
    
  } catch (error) {
    console.error('获取委托信息失败：', error)
    ElMessage.error('获取委托信息失败')
  }
}

/**
 * 提交评价
 */
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 检查是否已评价
    const hasRated = await checkIfRated()
    if (hasRated) {
      ElMessage.warning('您已经评价过这个委托了')
      return
    }
    
    submitLoading.value = true
    
    // 构建评价数据
    const rateData = {
      entrustId: route.params.id,
      rating: rateForm.rating,
      content: rateForm.content,
      tags: selectedTags.value,
      isAnonymous: rateForm.isAnonymous,
      submitTime: new Date().toISOString()
    }
    
    console.log('提交评价数据：', rateData)
    
    // TODO: 调用API提交评价
    // const res = await submitRate(rateData)
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('评价提交成功！')
    
    // 跳转到评价确认页
    router.push(`/campus-entrust/rate-confirm/${route.params.id}`)
    
  } catch (error) {
    console.error('提交评价失败：', error)
    if (error !== 'cancel') {
      ElMessage.error('提交评价失败，请检查表单信息')
    }
  } finally {
    submitLoading.value = false
  }
}

/**
 * 检查是否已评价
 * @returns {Promise<boolean>} 是否已评价
 */
const checkIfRated = async () => {
  try {
    // TODO: 调用API检查是否已评价
    // const res = await checkRateStatus(route.params.id)
    // return res.data.hasRated
    
    // 模拟检查
    return false
  } catch (error) {
    console.error('检查评价状态失败：', error)
    return false
  }
}

/**
 * 保存草稿
 */
const handleSave = async () => {
  try {
    const draftData = {
      entrustId: route.params.id,
      rating: rateForm.rating,
      content: rateForm.content,
      tags: selectedTags.value,
      isAnonymous: rateForm.isAnonymous,
      saveTime: new Date().toISOString()
    }
    
    // TODO: 调用API保存草稿
    // await saveRateDraft(draftData)
    
    // 模拟保存
    localStorage.setItem(`rate_draft_${route.params.id}`, JSON.stringify(draftData))
    
    ElMessage.success('草稿保存成功')
    
  } catch (error) {
    console.error('保存草稿失败：', error)
    ElMessage.error('保存草稿失败')
  }
}

/**
 * 加载草稿
 */
const loadDraft = () => {
  try {
    const draftData = localStorage.getItem(`rate_draft_${route.params.id}`)
    if (draftData) {
      const draft = JSON.parse(draftData)
      rateForm.rating = draft.rating || 0
      rateForm.content = draft.content || ''
      rateForm.isAnonymous = draft.isAnonymous || false
      selectedTags.value = draft.tags || []
      
      ElMessage.info('已加载保存的草稿')
    }
  } catch (error) {
    console.error('加载草稿失败：', error)
  }
}

/**
 * 返回上一页
 */
const goBack = () => {
  router.go(-1)
}

// 组件挂载时获取数据
onMounted(() => {
  fetchEntrustInfo()
  loadDraft()
})
</script>

<style scoped>
.rate-submit {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.rate-card {
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 16px;
}

.title {
  flex: 1;
  font-size: 18px;
  font-weight: 600;
}

.entrust-info {
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 32px;
}

.entrust-info h3 {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
}

.info-item {
  display: flex;
  margin-bottom: 8px;
}

.info-item .label {
  font-weight: 500;
  color: #606266;
  min-width: 100px;
}

.info-item .value {
  color: #303133;
  flex: 1;
}

.rate-form {
  margin-top: 20px;
}

.rating-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.rating-tip {
  font-size: 14px;
  color: #909399;
}

.tag-section {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag-item {
  cursor: pointer;
  transition: all 0.3s ease;
}

.tag-item:hover {
  transform: scale(1.05);
}

.anonymous-tip {
  font-size: 14px;
  color: #909399;
  margin-top: 8px;
}

:deep(.el-rate__text) {
  font-size: 14px;
  margin-left: 8px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}
</style> 